package org.zn.note.jdk.net;

import org.zn.note.common.util.IOUtil;
import org.zn.note.common.util.ThreadUtil;

import java.io.*;
import java.net.Socket;
import java.util.Arrays;

/**
 * @ClassName ServerHandler
 * @Author zn
 * @Date 2019/4/4 15:29
 **/
public class ServerHandler implements Runnable {
    private Socket socket;

    public ServerHandler(Socket socket) {
        this.socket = socket;
    }

    private void handler(InputStream in, OutputStream out) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
        while (true) {
            try {
                String readText = reader.readLine();
                ThreadUtil.printThread("[read] " + readText);
                String writeText = "server " + readText;
                ThreadUtil.printThread("[write] " + writeText);
                writer.write(writeText);
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
        }
    }

    @Override
    public void run() {
        InputStream in = null;
        OutputStream out = null;
        try {
            handler(socket.getInputStream(), socket.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtil.close(Arrays.asList(in, out, socket));
        }
    }
}
